//
//  WBHomeViewModel.swift
//  weibo
//
//  Created by 胡古古 on 2017/6/8.
//  Copyright © 2017年 hugugu. All rights reserved.
//

import UIKit
import YYModel
import SDWebImage

class WBHomeViewModel: NSObject {
    
    lazy var statusList: [WBStatusViewModel] = [WBStatusViewModel]()
    
    func loadData(isUp:Bool,callBack:@escaping (Bool,String)->()) {
        
        let token = WBUserAccountViewModel.sharedViewModel.userAccount?.access_token
        
        var maxId: Int64 = 0
        
        var sinceId: Int64 = 0
        
        
        if isUp {
            
            maxId = statusList.last?.status?.id ?? 0
            
            if maxId > 0 {
                
                maxId -= 1
            }
            
        } else {
            
            sinceId = statusList.first?.status?.id ?? 0
        }
        
        var message = "没有加载到最新微博数据"
        
        WBNetworkTools.sharedTools.requestStatuses(token: token!, maxId: maxId,sinceId:sinceId) { (response, error) in
            
            if error != nil {
                
                print("error:\(error!)")
                // 回调闭包
                callBack(false,message)
                return
            }
            
            let dict = response as! [String:Any]
            // 解析数据 通过字典获取微博数据
            let statusDicArray = dict["statuses"] as! [[String:Any]]
            
            let modelArray = NSArray.yy_modelArray(with: WBStatus.self, json: statusDicArray) as! [WBStatus]
            
            var tempArray = [WBStatusViewModel]()
            
            let group = DispatchGroup()
            
            for model in modelArray {
                
                let statusViewModel = WBStatusViewModel()
                statusViewModel.status = model
                
                tempArray .append(statusViewModel)
                
                if model.retweeted_status?.pic_urls?.count == 1{
                    
                    let imageURL = model.retweeted_status!.pic_urls!.first!.thumbnail_pic!
                    
                    group.enter()
                    
                    SDWebImageManager.shared().loadImage(with: URL(string:imageURL), options: [], progress: nil, completed: { (image, data, error, _, _, url) in
                        
                        print(url)
                        group.leave()
                        
                    })
                    
                    
                    if model.pic_urls?.count == 1 {
                        
                        let imageURL = model.pic_urls!.first!.thumbnail_pic!
                        group.enter()
                        
                        SDWebImageManager.shared().loadImage(with: URL(string:imageURL), options: [], progress: nil, completed: { (image, data, error, _, _, url) in
                            
                            print(url)
                            group.leave()
                            
                        })
                        
                    }
                    
                }
            }
            
//            self.statusList = tempArray
            if isUp {
                
                self.statusList.append(contentsOf: tempArray)
                
            } else {
                
                self.statusList.insert(contentsOf: tempArray, at: 0)
                
            }
            
            if tempArray.count > 0 {
                
                message = "加载了\(tempArray.count)条微博数据"
            }
            
            group.notify(queue: DispatchQueue.main, execute: { 
                
                print("图片下载成功")
                
                callBack(true,message)
            })
    
        }
        
    }

}
